<template>
    <el-input
      v-model="carNum"
      placeholder="字母和数字"
      class="input-with-select"
      @change="dataChange"
    >
      <template #prepend>
        <el-select v-model="carPre" placeholder="前缀" clearable @change="dataChange" style="width:120px" filterable>
          <el-option
              v-for="dict in dictOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
        </el-select>  
      </template>
    </el-input>
</template>

<script setup>
import useDictStore from '@/store/modules/dict';
import { getDicts } from '@/api/system/dict/data';

const emit = defineEmits(['update:modelValue'])

const dictOptions = ref([]);
const formType = ref('select');
const carPre = ref(null);
const carNum = ref(null);

const props = defineProps({
  modelValue: String
});

watch(() => props.modelValue, val => {
  if (val) {
      carPre.value = val.substring(0,1);
     carNum.value = val.substring(1);
  } else {
     carPre.value = null;
     carNum.value = null;
  }
},{ deep: true, immediate: true });

/** 加载字典 */
function loadDict(dictType) {
    const dicts = useDictStore().getDict(dictType);
    if (dicts) {
        dictOptions.value = dicts;
    } else {
        getDicts(dictType).then(resp => {
            dictOptions.value = resp.data.map(p => ({ label: p.dictLabel, value: p.dictValue, elTagType: p.listClass, elTagClass: p.cssClass }))
            useDictStore().setDict(dictType, dictOptions.value);
        });
    }
}

function dataChange() {  
  if(carPre.value != null && carNum.value != null)      {
    if(carNum.value.length > 7){
      carNum.value = carNum.value.substring(0,6);
    }
    let plate = carPre.value + carNum.value.toUpperCase();
    emit("update:modelValue", plate);
  }else{
    emit("update:modelValue", null);
  }
}

loadDict('car_prefix');

</script>

<style scoped>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>